package com.example.ws_test;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class HandlerExampleActivity extends AppCompatActivity {

    // 定义消息类型常量
    private static final int MSG_TYPE_RANDOM_LETTER = 1;
    private static final int MSG_TYPE_RANDOM_NUMBER = 2;
    private static final int MSG_TYPE_RANDOM_STRING = 3;
    private static final int MSG_TYPE_RANDOM_MIXED = 4;

    // UI组件
    private TextView resultTextView;
    private Button buttonRandomLetter;
    private Button buttonRandomNumber;
    private Button buttonRandomString;
    private Button buttonRandomMixed;
    private Button buttonCancelTasks;

    // 创建静态内部类Handler
    private static class MyHandler extends Handler {
        // 弱引用持有外部Activity，避免内存泄漏
        private final HandlerExampleActivity activity;

        public MyHandler(HandlerExampleActivity activity, Looper looper) {
            super(looper);
            this.activity = activity;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            
            // 获取当前时间戳
            String timestamp = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
            
            // 根据消息类型处理不同的逻辑
            switch (msg.what) {
                case MSG_TYPE_RANDOM_LETTER:
                    // 处理随机字母
                    char randomLetter = (char) msg.obj;
                    activity.updateResult("[" + timestamp + "] 随机字母: " + randomLetter);
                    break;
                
                case MSG_TYPE_RANDOM_NUMBER:
                    // 处理随机数字
                    int randomNumber = (int) msg.obj;
                    activity.updateResult("[" + timestamp + "] 随机数字: " + randomNumber);
                    break;
                
                case MSG_TYPE_RANDOM_STRING:
                    // 处理随机字符串
                    String randomString = (String) msg.obj;
                    activity.updateResult("[" + timestamp + "] 随机字符串: " + randomString);
                    break;
                
                case MSG_TYPE_RANDOM_MIXED:
                    // 处理混合字符
                    String mixedString = (String) msg.obj;
                    activity.updateResult("[" + timestamp + "] 混合字符: " + mixedString);
                    break;
                
                default:
                    // 未知消息类型
                    activity.updateResult("[" + timestamp + "] 未知消息类型: " + msg.what);
                    break;
            }
        }
    }

    // 创建Handler实例
    private MyHandler mHandler;
    private Random random;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_example);

        // 初始化UI组件
        resultTextView = findViewById(R.id.result_text_view);
        buttonRandomLetter = findViewById(R.id.button_random_letter);
        buttonRandomNumber = findViewById(R.id.button_random_number);
        buttonRandomString = findViewById(R.id.button_random_string);
        buttonRandomMixed = findViewById(R.id.button_random_mixed);
        buttonCancelTasks = findViewById(R.id.button_cancel_tasks);

        // 初始化Handler，使用主线程的Looper
        mHandler = new MyHandler(this, getMainLooper());
        random = new Random();

        // 设置按钮点击监听器
        buttonRandomLetter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 生成随机字母
                char randomLetter = (char) (random.nextInt(26) + 'A');
                
                // 创建消息
                Message message = mHandler.obtainMessage(MSG_TYPE_RANDOM_LETTER, randomLetter);
                
                // 发送消息，这里可以设置延迟，模拟异步操作
                int delayMillis = random.nextInt(1000) + 500; // 500-1500毫秒
                mHandler.sendMessageDelayed(message, delayMillis);
                
                // 显示提示
                Toast.makeText(HandlerExampleActivity.this, "正在生成随机字母，延迟" + delayMillis + "毫秒", Toast.LENGTH_SHORT).show();
            }
        });

        buttonRandomNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 生成随机数字
                int randomNumber = random.nextInt(1000);
                
                // 创建消息
                Message message = mHandler.obtainMessage(MSG_TYPE_RANDOM_NUMBER, randomNumber);
                
                // 发送消息
                int delayMillis = random.nextInt(1000) + 500;
                mHandler.sendMessageDelayed(message, delayMillis);
                
                // 显示提示
                Toast.makeText(HandlerExampleActivity.this, "正在生成随机数字，延迟" + delayMillis + "毫秒", Toast.LENGTH_SHORT).show();
            }
        });

        buttonRandomString.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 生成随机字符串
                String randomString = generateRandomString(8);
                
                // 创建消息
                Message message = mHandler.obtainMessage(MSG_TYPE_RANDOM_STRING, randomString);
                
                // 发送消息
                int delayMillis = random.nextInt(1000) + 500;
                mHandler.sendMessageDelayed(message, delayMillis);
                
                // 显示提示
                Toast.makeText(HandlerExampleActivity.this, "正在生成随机字符串，延迟" + delayMillis + "毫秒", Toast.LENGTH_SHORT).show();
            }
        });

        buttonRandomMixed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 生成混合字符
                String mixedString = generateMixedString(10);
                
                // 创建消息
                Message message = mHandler.obtainMessage(MSG_TYPE_RANDOM_MIXED, mixedString);
                
                // 发送消息
                int delayMillis = random.nextInt(1000) + 500;
                mHandler.sendMessageDelayed(message, delayMillis);
                
                // 显示提示
                Toast.makeText(HandlerExampleActivity.this, "正在生成混合字符，延迟" + delayMillis + "毫秒", Toast.LENGTH_SHORT).show();
            }
        });

        buttonCancelTasks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 移除所有待处理的消息
                mHandler.removeCallbacksAndMessages(null);
                
                // 显示提示
                Toast.makeText(HandlerExampleActivity.this, "已取消所有待处理任务", Toast.LENGTH_SHORT).show();
                updateResult("[" + new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date()) + "] 已取消所有待处理任务\n");
            }
        });
    }

    // 生成随机字母字符串
    private String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            char c = (char) (random.nextInt(26) + 'A');
            sb.append(c);
        }
        return sb.toString();
    }

    // 生成混合字符（字母、数字和特殊字符）
    private String generateMixedString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    // 更新结果显示
    public void updateResult(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在UI线程更新TextView
                String currentText = resultTextView.getText().toString();
                if (currentText.equals("等待处理...")) {
                    resultTextView.setText(text);
                } else {
                    resultTextView.setText(text + "\n" + currentText);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在Activity销毁时移除所有消息，避免内存泄漏
        mHandler.removeCallbacksAndMessages(null);
    }
}